#!/bin/bash
# author: Liu Kun
# date: 2021-04-04 19:29:05

# 样例 必须使用bash,由于使用了if [[ ]];then
# bash runTestNG.sh all 5
# runTestNG.sh all 5

# 接收外部入参
test_group_name=$1
test_thread_num=$2

# TestNG.xml
tng_xml=testng.xml

# 清理工作
# 目录 test-output
if [[ -d test-output ]];then
  echo "remove test-output"
  rm -rf test-output
fi
# 文件 testng.xml
if [[ -f ${tng_xml} ]];then
  echo "remove ${tng_xml}"
  rm -f ${tng_xml}
fi

# 生成 testng.xml
# shellcheck disable=SC2129
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>">>${tng_xml}
echo "<!DOCTYPE suite SYSTEM \"https://testng.org/testng-1.0.dtd\">">>${tng_xml}
echo "<suite name=\"fastTestNG\" verbose=\"1\" parallel=\"methods\" thread-count=\"${test_thread_num}\" data-provider-thread-count=\"${test_thread_num}\" >">>${tng_xml}
echo "  <test name=\"CurrentTest\" >">>${tng_xml}
echo "    <groups>">>${tng_xml}
echo "      <run>">>${tng_xml}

if [[ "${test_group_name}" == "all" ]]; then
  # shellcheck disable=SC2129
  echo "        <include name=\"api\" />">>${tng_xml}
  echo "        <include name=\"smoke\" />">>${tng_xml}
  echo "        <include name=\"function\" />">>${tng_xml}
else
  echo "        <include name=\"${test_group_name}\" />">>${tng_xml}
fi

# shellcheck disable=SC2129
echo "      </run>">>${tng_xml}
echo "    </groups>">>${tng_xml}
echo "    <classes>">>${tng_xml}
echo "      <class name=\"com.liukunup.testcase.TsApi\" />">>${tng_xml}
echo "      <class name=\"com.liukunup.testcase.TsSmoke\" />">>${tng_xml}
echo "      <class name=\"com.liukunup.testcase.TsFunction\" />">>${tng_xml}
echo "    </classes>">>${tng_xml}
echo "  </test>">>${tng_xml}
echo "</suite>">>${tng_xml}

# 显示 Maven 版本号
mvn --version

# 清理
mvn clean

# 打包 跳过测试
mvn package -DskipTests=true

# 项目名称
project_name=core
# 包名配置
jar_file=${project_name}-1.0.0-SNAPSHOT.jar

# 通过文件是否存在来判断编译打包结果
if [[ ! -f core/target/${jar_file} ]];then
  echo "maven build failed!"
  exit 1
fi

# 当前时间戳
timestamp=$(date "+%Y%m%d%H%M%S")

# 创建 workspace 文件夹
ws_dir="ws_${timestamp}"
mkdir "${ws_dir}"

# 拷贝 jar 包到当前 ws 路径下
cp -f core/target/${jar_file} "${ws_dir}"/

# 拷贝 testng.xml 文件到当前 ws 路径下
cp -f ${tng_xml} "${ws_dir}"/

# 执行测试
java -jar "${ws_dir}"/${jar_file}
